package com.heze.xunhuan.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heze.xunhuan.entity.Report;
import com.heze.xunhuan.exception.BusinessException;
import com.heze.xunhuan.mapper.ReportMapper;
import com.heze.xunhuan.service.ReportService;
import com.heze.xunhuan.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 举报服务实现类
 *
 * @author heze-xunhuan
 */
@Service
@RequiredArgsConstructor
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements ReportService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitReport(Long reporterId, String targetType, Long targetId, String reasonType,
                             String reasonDetail, Map<String, Object> evidence) {
        Report report = new Report();
        report.setReporterId(reporterId);
        report.setTargetType(targetType);
        report.setTargetId(targetId);
        report.setReasonType(reasonType);
        report.setReasonDetail(reasonDetail);
        report.setEvidence(evidence != null ? JSONUtil.toJsonStr(evidence) : null);
        report.setStatus("pending");
        report.setCreatedAt(LocalDateTime.now());

        this.save(report);
        return report.getId();
    }

    @Override
    public PageVO<Report> getReports(Integer page, Integer size, String status) {
        Page<Report> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Report> wrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            wrapper.eq(Report::getStatus, status);
        }
        wrapper.orderByDesc(Report::getCreatedAt);

        IPage<Report> reportPage = this.page(pageParam, wrapper);
        return new PageVO<>(reportPage.getRecords(), page, size, reportPage.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleReport(Long reportId, Long handlerId, String status, String handledResult) {
        Report report = this.getById(reportId);
        if (report == null) {
            throw new BusinessException(404, "举报不存在");
        }

        report.setHandlerId(handlerId);
        report.setStatus(status);
        report.setHandledResult(handledResult);
        report.setHandledAt(LocalDateTime.now());

        this.updateById(report);
    }
}

